<style lang="postcss" scoped>
.home-container {
}
</style>
<template>
  <section class="home-container">
    <MasterPage title>
      <!-- <div slot="searchContent" class="search-content-slot">
        <Form :model="formItem" :label-width="80">
          <Row>
            <Col span="6">
              <FormItem label="工号">
                <Input v-model="formItem.workNo"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem label="姓名">
                <Input v-model="formItem.name"></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>-->
      <div slot="search">
        <Button type="primary" icon="md-add" @click="new1()">添加</Button>
        <!-- <Button
          style="margin-right:5px;"
          type="error"
          icon="md-remove"
          @click="removeSelection()"
        >删除</Button>-->
      </div>
      <!-- <div slot="btns">
        <Button type="info" icon="ios-search" @click="search()">查询</Button>
      </div>-->
      <div slot="paddingContent">
        <Table :columns="columns1" :data="data1"></Table>
        <Modal :title="title" v-model="modal1" class-name="vertical-center-modal" :closable="false">
          <Form ref="formValidate" :model="formData" :label-width="80" :rules="ruleValidate">
            <FormItem label="角色代码" prop="role">
              <Input v-model="formData.role" :disabled="editdisable"></Input>
            </FormItem>
            <FormItem label="角色名">
              <Input v-model="formData.roleName"></Input>
            </FormItem>
            <FormItem label="模块">
              <Tree :data="moduleTree" show-checkbox></Tree>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="text" size="large" @click="model1Closed()">取消</Button>
            <Button type="primary" size="large" @click="ok()">确定</Button>
          </div>
        </Modal>
      </div>
      <div slot="pager">
        <!-- <Page
          :total="pageTotal"
          :current="pageNum"
          :page-size="pageSize"
          show-total
          show-sizer
          placement="top"
          @on-change="handlePage"
          @on-page-size-change="handlePageSize"
        />-->
      </div>
    </MasterPage>
  </section>
</template>
<script>
import MasterPage from '@/components/Master'
import { list, save, delete1 } from '@/services/role'
import { treeList } from '@/services/module'

export default {
  components: {
    MasterPage
  },
  async mounted() {
    console.log("role")
    this.data1 = await list()
    await this.setModuleTree()
  },
  methods: {
    async setModuleTree(row = {}) {
      let tree = await treeList()
      this.setTree(tree, row)
      console.log(tree)
      this.moduleTree = [{ expand: true, children: tree }]
    },
    setTree(data, row) {
      data.forEach(pm => {
        pm.title = pm.moduleName
        if (pm.children && pm.children.length > 0) {
          pm.expand = true
          this.setTree(pm.children, row)
        } else {
          //匹配选中
          if (row.moduleUrls && row.moduleUrls.indexOf(pm.url) >= 0)
            pm.checked = true
        }
      })
    },
    async remove(row) {
      try {
        await delete1(row.id)
        this.$Message.info("操作成功");
        this.data1 = await list()
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    async edit(row) {
      console.log(row)
      await this.setModuleTree(row)
      this.formData = Object.assign({}, row)
      this.title = "配置"
      this.editdisable = true
      this.modal1 = true

    },
    new1() {
      this.title = "新增"
      this.editdisable = false
      this.modal1 = true
    },
    async ok() {
      let valid = await this.$refs.formValidate.validate()
      if (!valid) return
      if (!this.moduleTree || Object.keys(this.moduleTree).length == 0) {
        this.moduleList = []
      } else {
        let moduleList = [...this.moduleTree[0].children]
        this.moduleList = this.setModuleList(moduleList)
      }

      let old = this.moduleList.find(m => m.role == this.formData.role)
      if (!old || this.title == "配置") {
        //无重复url,直接保存
        this.doSave()
      } else {
        //提示保存
        this.$Modal.confirm({
          title: "警告",
          content: "存在相同角色,继续保存将更新角色信息,是否确认!",
          onOk: () => {
            this.doSave()
          }
        })
      }
    },
    async doSave() {
      try {
        let moduleIds = []
        let moduleUrls = []
        this.moduleList.forEach(m => {
          if (m.checked) {
            moduleIds.push(m.id)
            moduleUrls.push(m.url)
          }
        })
        // let moduleIds = this.moduleList.map(m => {
        //   if (m.checked) return m.id
        // })
        // moduleIds = moduleIds.filter(m => m)
        console.log(moduleIds)
        this.formData.moduleIds = moduleIds.join(",")
        this.formData.moduleUrls = moduleUrls.join(",")
        //重复角色提示
        await save(this.formData)
        this.$Message.info("操作成功");
        this.model1Closed()
        this.data1 = await list()
      } catch (err) {
        this.$Notice.error({ title: '操作失败', desc: err });
      }
    },
    setModuleList(moduleList, allModule = []) {
      let noChildren = moduleList.filter(m => !m.children || m.children.length == 0)
      allModule = allModule.concat(...noChildren)
      let children = []
      moduleList.forEach(m => {
        if (m.children && m.children.length > 0)
          children = children.concat(...m.children)
      })
      // console.log("1==", moduleList, allModule, children)
      return children.length > 0 ? this.setModuleList(children, allModule) : allModule
    },
    model1Closed() {
      this.modal1 = false
      this.formData = {}
      this.$refs.formValidate.resetFields()
    },

  },
  data() {
    return {
      moduleList: [],
      moduleTree: [],
      editdisable: false,
      modal1: false,
      title: "",
      formData: {},
      columns1: [
        {
          title: '角色',
          key: 'role'
        },
        {
          title: '角色名',
          key: 'roleName'
        },
        {
          title: '操作',
          // key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.edit(params.row)
                  }
                }
              }, '配置'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.remove(params.row)
                  }
                }
              }, '删除'),
            ]);
          }
        }
      ],
      ruleValidate: {
        role: [
          { required: true, message: '必填', trigger: 'blur' },
        ],
      },
      data1: []
    }
  },
}
</script>
